package com.tsystems.clientEmployee.gui;

import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tsysstems.clientEmployee.ClientEmployee;
import com.tsystems.entities.Passenger;
import com.tsystems.entities.Station;
import com.tsystems.entities.TimeTableElement;
import com.tsystems.entities.Train;

public class PassengersManagementPanel extends JPanel {

	Passenger currentPassenger;
	PassengerTable passengerTable = new PassengerTable();
	private static final long serialVersionUID = 6489712085149821505L;

	Logger logger = LoggerFactory.getLogger(getClass());

	public PassengersManagementPanel() {
		super(new GridBagLayout());

		setBorder(new TitledBorder("Управление пассажирами"));

		passengerTable.updateTable(ClientEmployee.getInstance()
				.viewPassengersBase());
		passengerTable.setSelectListener(new ListSelectionListener() {

			public void valueChanged(ListSelectionEvent e) {
				Object object = e.getSource();
				if (object instanceof Passenger) {
					currentPassenger = (Passenger) object;
				}

			}
		});

		add(new JScrollPane(passengerTable), new GridBagConstraints(0, 0, 1, 1,
				1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				new Insets(0, 0, 0, 0), 0, 0));
		add(createButtonPanel(), new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0,
				GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
				new Insets(-5, 0, 0, 0), 0, 0));

	}

	public JPanel createButtonPanel() {

		JPanel result = new JPanel(new FlowLayout());
		JButton addPassenger = new JButton("Добавить пассажира");
		addPassenger.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				Passenger passenger = AddPassengerPanel.showDialog(JOptionPane
						.getRootFrame());
				if (passenger == null) {
					return;
				}
				String result = ClientEmployee.getInstance().addPassenger(
						passenger);
				if (result == null) {
					JOptionPane
							.showMessageDialog(PassengersManagementPanel.this,
									"Произошла внутренняя ошибка приложения, обратитесь к администратору.");
				}
				if (result.equals("Поздравляем! Регистрация прошла успешно!")) {
					passengerTable.updateTable(ClientEmployee.getInstance()
							.viewPassengersBase());
				} else {
					JOptionPane.showMessageDialog(
							PassengersManagementPanel.this, result);
				}

			}
		});

		JButton editPassenger = new JButton("Изменить пассажира");
		editPassenger.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				Passenger selectedPassenger = passengerTable
						.getSelectedPassenger();
				if (selectedPassenger == null) {
					return;
				}
				Passenger passenger = AddPassengerPanel.showDialog(
						JOptionPane.getRootFrame(), selectedPassenger);
				if (passenger == null) {
					return;
				}
				
				String result= ClientEmployee.getInstance().editPassenger(passenger);
				
				if(result==null){
					JOptionPane
					.showMessageDialog(PassengersManagementPanel.this,
							"Возникла внутренняя ошибка приложения, обратитесь к администратору!");
				}
				
				if (result.equals("Изменение пассажира прошло успешно!")) {
					updateTable();
				} else {
					JOptionPane
							.showMessageDialog(PassengersManagementPanel.this,
									result);
				}

			}
		});
		JButton removePassenger = new JButton("Удалить пассажира");
		removePassenger.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				Passenger passenger = passengerTable.getSelectedPassenger();
				if (passenger == null) {
					return;
				}
				if (JOptionPane
						.showConfirmDialog(
								PassengersManagementPanel.this,
								"Вы уверены что хотите удалить пассажира и все связанные с ним билеты?",
								"Предупреждение!!", JOptionPane.YES_NO_OPTION) == 0) {

					String result = ClientEmployee.getInstance()
							.removePassenger(passenger);

					if (result == null) {
						JOptionPane
								.showMessageDialog(
										PassengersManagementPanel.this,
										"Возникла внутрнняя ошибка приложения, обратитесь к администратору!");
					}
					if (result.equals("Удаление пассажира прошло успешно!")) {
						passengerTable.updateTable(ClientEmployee.getInstance()
								.viewPassengersBase());
					} else {
						JOptionPane.showMessageDialog(
								PassengersManagementPanel.this, result);
					}
				}

			}
		});
		Vector<TimeTableElement> tteVector = new Vector<TimeTableElement>();
		tteVector.add(new TimeTableElement(new Train("Все поезда", 0),
				new Station(""), new Station(""), null, null));
		tteVector.addAll(ClientEmployee.getInstance().viewTimeTableElements());
		JComboBox timeTableElementsBox = new JComboBox(tteVector);

		timeTableElementsBox.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				JComboBox box = (JComboBox) e.getSource();
				Object object = box.getSelectedItem();

				if (object instanceof TimeTableElement) {
					TimeTableElement element = (TimeTableElement) object;
					if (element.getTrain().getNumber().equals("Все поезда")) {
						passengerTable.updateTable(ClientEmployee.getInstance()
								.viewPassengersBase());
					} else {
						passengerTable.updateTable(ClientEmployee.getInstance()
								.viewPassengersOnTrain(element));
					}
				}

			}
		});

		result.add(addPassenger);
		result.add(editPassenger);
		result.add(removePassenger);
		result.add(new JLabel("Зарегистрированы на:"));
		result.add(timeTableElementsBox);

		return result;
	}

	public void updateTable() {

		passengerTable.updateTable(ClientEmployee.getInstance()
				.viewPassengersBase());
	}
}
